package com.jingyanzi.member.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.marketing.domain.PresentDo;
import com.jingyanzi.marketing.domain.PresentExchangeDo;
import com.jingyanzi.member.api.MemberConfigClientAPI;
import com.jingyanzi.member.api.PresentCientAPI;
import com.jingyanzi.member.api.PresentExchangeCientAPI;
import com.jingyanzi.member.dao.MCustomerFamilyMapper;
import com.jingyanzi.member.dao.MMemberMapper;
import com.jingyanzi.member.domain.AccountDO;
import com.jingyanzi.member.domain.CustomerDO;
import com.jingyanzi.member.domain.CustomerExtraDO;
import com.jingyanzi.member.domain.CustomerFamilyDO;

import com.jingyanzi.member.domain.IntegralDO;
import com.jingyanzi.member.domain.MemberDO;
import com.jingyanzi.member.domain.result.ResultDO;
import com.jingyanzi.member.domain.result.ResultSupport;
import com.jingyanzi.member.entity.MCustomerFamily;
import com.jingyanzi.member.entity.MCustomerFamilyExample;
import com.jingyanzi.member.entity.MMember;
import com.jingyanzi.member.entity.MMemberExample;
import com.jingyanzi.member.entity.MMemberExample.Criteria;

import com.jingyanzi.member.query.CustomerFamilyQueryDO;
import com.jingyanzi.member.query.MemberQueryDO;
import com.jingyanzi.member.service.IAccountService;
import com.jingyanzi.member.service.ICustomerExtraService;
import com.jingyanzi.member.service.ICustomerFamilyService;
import com.jingyanzi.member.service.ICustomerService;
import com.jingyanzi.member.service.IIntegralLogService;
import com.jingyanzi.member.service.IIntegralService;
import com.jingyanzi.member.service.IMemberService;
import com.jingyanzi.member.util.BeanUtilsExtends;
import com.jingyanzi.member.util.MemberConstant;
import com.jingyanzi.privilege.domain.EmployeeDO;
import com.jingyanzi.privilege.factory.PrivilegeFactory;
import com.jingyanzi.sys.domain.MemberGradeDO;



@Service("memberService")
public class MemberServiceImpl extends BaseServiceImpl implements IMemberService {

	private static Logger logger = Logger.getLogger(MemberServiceImpl.class);
	
	@Autowired
	private MMemberMapper memberMapper;
	
	@Autowired
	private MCustomerFamilyMapper customerFamilyMapper;
	
	@Autowired
	private ICustomerService customerService;

	@Autowired
	private ICustomerFamilyService customerFamilyService;
	
	@Autowired
	private ICustomerExtraService customerExtraService;

	@Autowired
	private IAccountService accountService;

	@Autowired
	private IIntegralService integralService;

	@Autowired
	private IIntegralLogService integralLogService;

	//@Autowired
	//private ICustomerSolrService solrService;
	
	@Autowired
	private MemberConfigClientAPI memberConfigClientAPI;
	
	@Autowired
	private PresentCientAPI presentCientAPI;

	@Autowired
	private PresentExchangeCientAPI presentExchangeCientAPI;
	

	/** 客户首次开通会员 */
	public ResultDO add(MemberDO domain) {

		MMember entity = new MMember();

		ResultSupport result = BeanUtilsExtends.copy(entity, domain);
		if (!result.isSuccess()) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "转换对象失败");
			result.setSuccess(false);
			return result;
		}

		CustomerFamilyQueryDO query = new CustomerFamilyQueryDO();
		query.setCustomerId(domain.getCustomId());
		query.setIsFirst(1);
		// 获取客户信息
		ResultDO res = customerFamilyService.query(query);
		if (!res.isSuccess()) {
			result.setErrorCode(ResultDO.MEMBER_ADD_ERROR);
			result.setErrorMsg("获取客户信息失败");
			result.setSuccess(false);
			return result;
		}

		List<CustomerFamilyDO> listFamily = (List<CustomerFamilyDO>) res.getModel(ResultSupport.FIRST_MODEL_KEY);

		CustomerFamilyDO domain2 = listFamily.get(0);
		entity.setGender(domain2.getGender());
		entity.setName(domain2.getName());
		entity.setTelephone(domain2.getTelephone());
		if(StringUtils.isNotEmpty(domain2.getBirthdayStamp())) {
			entity.setBirthday(new Date(Integer.parseInt(domain2.getBirthdayStamp())));
		}

		Calendar calendar = new GregorianCalendar();

		calendar.setTime(Calendar.getInstance().getTime());
		calendar.add(Calendar.YEAR, 1);// 把日期往后增加一年.整数往后推,负数往前移动
		entity.setExpires(calendar.getTime());
		entity.setJionTime(Calendar.getInstance().getTime());
		entity.setId(domain.getCustomId());
		entity.setPayment(domain.getMemberPayment());
		if (isNumberInValid(domain.getStatus())) {
			entity.setStatus(MemberConstant.MEMBER_STATUS_NOT_ACTIVITY);
		}
		entity.setIsDelete(MemberConstant.DB_ISDEL_NO);
		entity.setJionType(MemberConstant.MEMBER_JOIN_TYPE_BUY); // 入会方式默认：购买会员
		// 获取员工信息
		if (isNumberInValid(entity.getEmployeeId())) {
			entity.setEmployeeId(null);
		} else if (StringUtils.isEmpty(entity.getEmployeeName())) {
			EmployeeDO employeeDO = getEmployeeById(entity.getEmployeeId());
			if (null != employeeDO) {
				entity.setEmployeeName(employeeDO.getRealName());
			}
		}
		// 1. 新增会员信息
		int r = -1;
		try {
			r = memberMapper.insert(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "开通会员失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "开通会员失败");
			result.setSuccess(false);
			return result;
		}

		// 2. 创建积分表
		IntegralDO integralDO = new IntegralDO();
		integralDO.setId(domain.getCustomId());
		ResultDO res2 = integralService.add(integralDO);
		if (!res2.isSuccess()) {
			result.setErrorCode(ResultDO.MEMBER_ADD_ERROR);
			result.setErrorMsg("创建客户积分信息失败");
			result.setSuccess(false);
			return result;
		}

		// 3、是否发送短信事件
		if (domain.getIsSms() == 1) {
			//addSms(entity);
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, entity.getId());

		return result;
	}

	@Override
	public ResultDO reOpenMember(MemberDO domain, boolean isRenewal) {

		ResultSupport result = new ResultSupport();

		MMember entity = new MMember();
		entity.setId(domain.getCustomId());
		if (!isRenewal || StringUtils.isEmpty(domain.getExpireStamp())) {
			//重新开卡或有效期为空时，以当前时间计算会员有效期 
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(Calendar.getInstance().getTime());
			calendar.add(Calendar.YEAR, 1);// 把日期往后增加一年.整数往后推,负数往前移动
			entity.setExpires(calendar.getTime());
		} else {
			// 会员续费，在原有效期基础上顺延一年
			entity.setExpires(new Date(Long.parseLong(domain.getExpireStamp())));
		}
		entity.setAutoRenew(domain.getAutoRenew());
		entity.setMemberType(domain.getMemberType());
		entity.setPayment(domain.getMemberPayment());
		if (null != domain.getEmployeeId() && domain.getEmployeeId() > 0) {
			entity.setEmployeeId(domain.getEmployeeId());
			entity.setEmployeeName(domain.getEmployeeName());
		}
		if (!isRenewal) {
			// 重开会员
			entity.setJionType(MemberConstant.MEMBER_JOIN_TYPE_BUY);
			entity.setJionTime(Calendar.getInstance().getTime());
			entity.setIsDelete(MemberConstant.DB_ISDEL_NO);
			entity.setStatus(MemberConstant.MEMBER_STATUS_NOT_ACTIVITY);
		}
		entity.setModifi(domain.getAuthor());
		entity.setModifitime(Calendar.getInstance().getTime());

		int r = -1;
		try {
			r = memberMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "开通会员失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "开通会员失败");
			result.setSuccess(false);
			return result;
		}

		// 如果是重新开通会员，则重新开启积分表； 续费时，不操作积分表
		if (!isRenewal) {
			IntegralDO integralDO = new IntegralDO();
			ResultDO res2 = integralService.get(domain.getCustomId());
			if (res2.isSuccess()) {
				integralDO = (IntegralDO) res2.getModel(ResultSupport.FIRST_MODEL_KEY);
				integralDO.setTotleIntegral(0);
				integralDO.setUseIntegral(0);
				integralDO.setChangeNumber(0);
				integralDO.setExp(0);
				integralDO.setIsDelete(MemberConstant.DB_ISDEL_NO);
				integralDO.setModifi(domain.getAuthor());
				res2 = integralService.modifi(integralDO);
			} else {
				integralDO.setId(domain.getCustomId());
				res2 = integralService.add(integralDO);
			}
			if (!res2.isSuccess()) {
				result.setErrorCode(ResultDO.MEMBER_ADD_ERROR);
				result.setErrorMsg("创建客户积分信息失败");
				result.setSuccess(false);
				return result;
			}
		}
		// 3、是否发送短信事件
		if (domain.getIsSms() == 1) {
			//addSms(entity);
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, entity.getId());
		return result;
	}

	/** 发送短信 *//*
	private boolean addSms(MMember entity) {
		if (StringUtils.isEmpty(entity.getTelephone())) {
			logger.error(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + " 手机号码为空");
			return false;
		}
		MSmsRecord smsRecord = new MSmsRecord();
		smsRecord.setMemberId(entity.getId());
		smsRecord.setName(entity.getName());
		smsRecord.setMobile(entity.getTelephone());
		smsRecord.setTitle("会员开卡短信");
		// TODO: 短信内容模板
		smsRecord.setContent("会员开卡短信");
		smsRecord.setStatus(1);
		// sms_record表新增数据
		try {
			int r = smsRecordMapper.insert(smsRecord);
			if (r < 1) {
				logger.error(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + " 短信记录表写入失败");
				return false;
			}
		} catch (Exception e) {
			logger.error(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + " 短信记录表写入失败：" + e.getMessage());
			return false;
		}
		return true;
	}*/

	public ResultDO validateMobile(String telephone) {

		ResultSupport result = new ResultSupport();

		MMemberExample example = new MMemberExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andTelephoneEqualTo(telephone).andIsDeleteEqualTo(1);

		int count = 0;
		try {
			count = memberMapper.countByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "验证失败");
			result.setSuccess(false);
			return result;
		}
		MemberDO domain = new MemberDO();
		domain.setCount(count);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, domain);
		return result;
	}

	private MemberDO setMemberInfo(MemberDO memberDO) {
		if (null == memberDO) {
			return null;
		}
		// 获取客户信息
		ResultDO res1 = customerExtraService.get(memberDO.getId());
		if (!res1.isSuccess()) {
			return null;
		}

		CustomerExtraDO customerExtrDO = (CustomerExtraDO) res1.getModel(ResultSupport.FIRST_MODEL_KEY);

		CustomerFamilyQueryDO query = new CustomerFamilyQueryDO();
		query.setCustomerId(memberDO.getCustomId());
		query.setIsFirst(1);
		// 获取客户信息
		ResultDO res = customerFamilyService.query(query);
		

		List<CustomerFamilyDO> listFamily = (List<CustomerFamilyDO>) res.getModel(ResultSupport.FIRST_MODEL_KEY);

		CustomerFamilyDO domain2 = listFamily.get(0);
		memberDO.setConsumeCount(customerExtrDO.getConsumeCount());
		memberDO.setConsumeDateStamp(customerExtrDO.getConsumeDate());
		memberDO.setTotle(customerExtrDO.getConsumeMoney());
		memberDO.setTelephone(domain2.getTelephone());
		if (null != domain2.getBirthdayStamp()) {
			memberDO.setBirthdayStamp(domain2.getBirthdayStamp());
		}
		if (domain2.getGender() == 1) {
			memberDO.setGenderName("男");
		} else {
			memberDO.setGenderName("女");
		}

		ResultDO res2 = accountService.get(memberDO.getId());
		if (!res2.isSuccess()) {
			return null;
		}

		memberDO.setBalance(((AccountDO) res2.getModel(ResultSupport.FIRST_MODEL_KEY)).getBalance());

		ResultDO res3 = integralService.get(memberDO.getId());
		if (!res3.isSuccess()) {
			return null;
		}
		IntegralDO integralDO = (IntegralDO) res3.getModel(ResultSupport.FIRST_MODEL_KEY);
		memberDO.setIntegral(integralDO.getTotleIntegral());
		MemberGradeDO domain3 = memberConfigClientAPI.getMemberGradeDO(integralDO.getExp());

		memberDO.setGradeId(domain3.getId());
		memberDO.setGradeName(domain3.getName());
		memberDO.setDiscount(domain3.getDiscount());
		// TODO: 优惠券数量（暂时没有用）
		// memberDO.setDiscountCount(0);
		return memberDO;
	}

	/** 会员注销 */
	public ResultDO remove(Integer id, String cancelInfo) {

		ResultSupport result = new ResultSupport();

		MMember entity = new MMember();

		entity.setId(id);
		entity.setCancelInfo(cancelInfo);
		entity.setIsDelete(-1);

		int r = -1;

		try {
			r = memberMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "删除会员失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "删除会员失败");
			result.setSuccess(false);
			return result;
		}

		// 更新客户表客户类型为成交客户
		ResultDO res = customerService.get(id);
		if (!res.isSuccess()) {
			result.setErrorCode(ResultDO.MEMBER_ADD_ERROR);
			result.setErrorMsg("获取客户信息失败");
			result.setSuccess(false);
			return result;
		}

		CustomerDO customerDO = (CustomerDO) res.getModel(ResultSupport.FIRST_MODEL_KEY);
		customerDO.setIsMember(MemberConstant.CUSTOMER_NORMAL);
		customerDO.setStatus(MemberConstant.CUSTOMER_TYPE_TRADE);
		customerService.modifi(customerDO);

		// 积分清零
		ResultDO res2 = integralService.get(id);
		IntegralDO integralDO = new IntegralDO();
		if (res2.isSuccess()) {
			integralDO = (IntegralDO) res2.getModel(ResultSupport.FIRST_MODEL_KEY);
			// 会员不存在或会员已失效
			if (null == integralDO || integralDO.getIsDelete() != 1) {
				result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "未查到该会员的积分信息");
				result.setSuccess(false);
				return result;
			}
		}
		// 写入积分记录
		IntegralDO integral = new IntegralDO();
		integral.setMemberId(id);
		integral.setIntegral(integralDO.getTotleIntegral());
		integral.setOpType(MemberConstant.MEMBER_INTEGRAL_MINUS);
		integral.setOpInfo("会员注销 积分清零");
		integralLogService.addLog(integral);
		// 删除积分表数据
		ResultDO res1 = integralService.remove(id);
		if (!res1.isSuccess()) {
			result.setErrorCode(ResultDO.MEMBER_REMOVE_ERROR);
			result.setErrorMsg("删除账户积分信息");
			result.setSuccess(false);
			return result;
		}
		return result;
	}

	public ResultDO modifi(MemberDO domain) {

		MMember entity = new MMember();

		ResultSupport result = BeanUtilsExtends.copy(entity, domain);
		if (!result.isSuccess()) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "转换对象失败");
			result.setSuccess(false);
			return result;
		}

		entity.setModifitime(Calendar.getInstance().getTime());

		int r = -1;
		try {
			r = memberMapper.updateByPrimaryKeySelective(entity);
			// 更新客户首要联系人信息
			MCustomerFamily family = new MCustomerFamily();
			family.setCustomerId(entity.getId());
			family.setBirthday(entity.getBirthday());
			entity.setModifitime(Calendar.getInstance().getTime());

			MCustomerFamilyExample example = new MCustomerFamilyExample();
			MCustomerFamilyExample.Criteria criteria = example.createCriteria();
			criteria.andCustomerIdEqualTo(entity.getId());
			criteria.andIsFirstEqualTo(MemberConstant.FAMILY_IS_FIRST).andIsDeleteEqualTo(1);
			customerFamilyMapper.updateByExampleSelective(family, example);

			// 更新solr
			//solrService.addRecord(entity.getId());
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "修改会员信息失败");
			result.setSuccess(false);
			return result;
		}
		if (r < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "修改会员信息失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO get(Integer id) {

		ResultSupport result = new ResultSupport();

		if (id < 1) {
			result.setErrorCode(ResultDO.QUERY_VALUE_SET_ERROR);
			result.setErrorMsg(ResultDO.QUERY_VALUE_IS_NULL_ERROR_MSG + "或小于1");
			result.setSuccess(false);
			return result;
		}

		MMember entity = null;
		try {
			entity = memberMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "获取会员信息失败");
			result.setSuccess(false);
			return result;
		}

		MemberDO memberDO = setMemberInfo(getMemberDO(entity));
		if (memberDO == null) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "获取会员信息失败");
			result.setSuccess(false);
			return result;
		}
		result.setModel(ResultSupport.FIRST_MODEL_KEY, memberDO);
		return result;
	}

	public ResultDO getMember(Integer id) {
		
		ResultSupport result = new ResultSupport();
		
		if (isNumberInValid(id)) {
			result.setErrorCode(ResultDO.QUERY_VALUE_SET_ERROR);
			result.setErrorMsg(ResultDO.QUERY_VALUE_IS_NULL_ERROR_MSG + "或小于1");
			result.setSuccess(false);
			return result;
		}
		
		MMember entity = null;
		try {
			entity = memberMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "获取会员信息失败");
			result.setSuccess(false);
			return result;
		}
		
		MemberDO memberDO = getMemberDO(entity);
		if (memberDO == null) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "获取会员信息失败");
			result.setSuccess(false);
			return result;
		}
		result.setModel(ResultSupport.FIRST_MODEL_KEY, memberDO);
		return result;
	}

	@Override
	public ResultDO query(MemberQueryDO query) {

		ResultSupport result = new ResultSupport();

		List<MMember> list = null;

		MMemberExample example = new MMemberExample();

		Criteria createCriteria = example.createCriteria();

		if (query.getNameOrTel() != null) {
			if (isChinaPhoneLegal(query.getNameOrTel())) {
				createCriteria.andTelephoneEqualTo(query.getNameOrTel());
			} else {
				createCriteria.andNameEqualTo(query.getNameOrTel());
			}
		}

		createCriteria.andIsDeleteEqualTo(1).andStatusNotEqualTo(0);

		List<MemberDO> doList = null;

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = memberMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}

		try {
			list = memberMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "获取会员信息失败");
			result.setSuccess(false);
			return result;
		}

		doList = getMemberDOList(list);

		if (doList == null) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "填充数据失败");
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, doList);

		return result;
	}

	@Override
	public ResultDO activity(MemberDO domain) {

		ResultSupport result = new ResultSupport();
		MMember entity = memberMapper.selectByPrimaryKey(domain.getId());
		if (entity.getStatus() == MemberConstant.MEMBER_STATUS_NOT_ACTIVITY) {
			entity.setStatus(MemberConstant.MEMBER_STATUS_NORMAL);
			entity.setModifitime(Calendar.getInstance().getTime());
			int r = -1;
			try {
				r = memberMapper.updateByPrimaryKeySelective(entity);
			} catch (Exception e) {
				e.printStackTrace();
				result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "会员激活失败");
				result.setSuccess(false);
				return result;
			}
			if (r < 1) {
				result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "会员激活失败");
				result.setSuccess(false);
				return result;
			}
			
			// 新增时，更新solr数据
			//solrService.addRecord(domain.getId());
		}
		// TODO: 查询短信发送记录表中的待发记录，有则发送
		return result;
	}

	public ResultDO exchangeGift(MemberDO domain) {
		ResultSupport result = new ResultSupport();
		PresentDo presentDo = null;
		// 写入积分表及积分记录表
		IntegralDO integralDO = new IntegralDO();
		integralDO.setMemberId(domain.getMemberId());
		integralDO.setIntegral(domain.getTotalIntegral());
		integralDO.setOpType(MemberConstant.MEMBER_INTEGRAL_MINUS);
		integralDO.setOpInfo("礼品兑换");
		integralDO.setModifi(domain.getModifi());

		ResultDO res = integralLogService.addLog(integralDO);
		if (!res.isSuccess()) {
			result.setSuccess(false);
			result.setErrorCode(res.getErrorCode());
			result.setErrorMsg(res.getErrorMsg());
			return result;
		}

		// 写入礼品兑换记录
		for (int i = 0; i < domain.getIds().length; i++) {
			
			presentDo = presentCientAPI.get(domain.getIds()[i]);
			if (presentDo == null) {
				result.setErrorCode(ResultDO.MEMBER_EXCHANGEGIFT_ERROR);
				result.setErrorMsg("获取礼品信息失败");
				result.setSuccess(false);
				return result;
			}
			if (presentDo.getSurplus() < 1) {
				result.setErrorCode(ResultDO.MEMBER_EXCHANGEGIFT_ERROR);
				result.setErrorMsg("礼品数量小于1");
				result.setSuccess(false);
				return result;
			}
			presentDo.setSurplus(presentDo.getSurplus() - 1);
			presentDo.setExchange(presentDo.getExchange() + 1);
			//更新礼品信息表
			presentCientAPI.edit(presentDo);
			
			// 写入礼品兑换表
			PresentExchangeDo presentExchangeDo = new PresentExchangeDo();
			presentExchangeDo.setIdentifier(domain.getMemberId());
			presentExchangeDo.setPresentId(presentDo.getId());
			presentExchangeDo.setPresentName(presentDo.getName());
			presentExchangeDo.setIntegral(presentDo.getIntegral());
			presentExchangeDo.setExchanges(1); // 兑换数，页面控制为每次兑换1个
			presentExchangeCientAPI.add(presentExchangeDo);
		}
		return result;
	}

	/**
	 * 对象拷贝单个实体到对象中
	 * 
	 * @param obj
	 * @return 返回DO对象
	 */
	public MemberDO getMemberDO(MMember obj) {
		if (obj == null)
			return null;
		MemberDO dst = new MemberDO();
		dst = BeanUtilsExtends.copyProperties(dst, obj) ? dst : null;
		String joinTypeName = "";
		if (obj.getJionType() == MemberConstant.MEMBER_JOIN_TYPE_BUY) {
			joinTypeName = "购买年卡";
		} else if (obj.getJionType() == MemberConstant.MEMBER_JOIN_TYPE_RECHARGE) {
			joinTypeName = "充值开卡";
		}
		dst.setJionTypeName(joinTypeName);
		if (obj.getJionTime() != null) {
			dst.setJionTimeStamp(String.valueOf(obj.getJionTime().getTime()));
		}
		if (obj.getExpires() != null) {
			dst.setExpireStamp(String.valueOf(obj.getExpires().getTime()));
		}
		if(obj.getRecommendType() != null) {
			if (obj.getRecommendType() == 1) {
				if (obj.getRecommendId() != null) {
					ResultDO res = customerFamilyService.get(obj.getRecommendId());
					if (res.isSuccess()) {
						CustomerFamilyDO customerFamilyDO = (CustomerFamilyDO) res.getModel(ResultSupport.FIRST_MODEL_KEY);
						dst.setRecommendName(customerFamilyDO.getName());
					}
				}
			} else {
				if (obj.getRecommendId() != null) {
					com.jingyanzi.privilege.domain.result.ResultDO res1 = PrivilegeFactory.getEmployeeService()
							.getEmployee(obj.getRecommendId());
					EmployeeDO employeeDO = (EmployeeDO) res1.getModel(ResultSupport.FIRST_MODEL_KEY);
					dst.setRecommendName(employeeDO.getRealName());
				}
			}
		}
		return dst;

	}

	/**
	 * 对象拷贝多个实体到列表中
	 * 
	 * @param List
	 * @return List
	 */
	public List<MemberDO> getMemberDOList(List<MMember> list) {
		List<MemberDO> result = new ArrayList<MemberDO>();
		if (list != null && !list.isEmpty()) {
			for (MMember member : list) {
				MemberDO memberDO = getMemberDO(member);
				if (memberDO != null) {
					result.add(setMemberInfo(memberDO));
				}
			}
		}

		return result;
	}
	
	public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
		String regExp = "^((13[0-9])|(14[5-9]|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8,9])))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

}
